package net.learn2develop.GPS;

import net.learn2develop.DB.DatabaseHelper;
import net.learn2develop.GPS.R;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class Search extends ListActivity {
	
	protected EditText searchText;
	protected SQLiteDatabase db;
	protected Cursor cursor;
	protected ListAdapter adapter;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.emptymain);
        
        searchText = (EditText) findViewById(R.id.searchText);
    	DatabaseHelper dbh = new DatabaseHelper(this);
    	db = dbh.getWritableDatabase();
    	//Actualiza la tabla SIEMPRE, via NETWORK
    	//dbh.onUpgrade(db, 1, 2);
    }
    
    public void onListItemClick(ListView parent, View view, int position, long id) {
    	Intent intent = new Intent(this, PlaceInMap.class);
    	Cursor cursor = (Cursor) adapter.getItem(position);
    	intent.putExtra("PLACE_ID", cursor.getInt(cursor.getColumnIndex("_id")));
    	startActivity(intent);
    }
    
    public void search(View view) {
    	// || is the concatenation operation in SQLite, we use MATCH in FTS3 and * by %
    	cursor = db.rawQuery("SELECT _id, nameplace, latitud, longitud, address FROM places WHERE nameplace LIKE ?", 
				new String[]{"%" + searchText.getText().toString() + "%"});
    	adapter = new SimpleCursorAdapter(
				this, 
				R.layout.places_list_item, 
				cursor, 
				new String[] {"nameplace", "address", "latitud", "longitud"}, 
				new int[] {R.id.placeName, R.id.address,  R.id.latitude, R.id.longitude});
		setListAdapter(adapter);
    }
    
    
    
}
